package wangdao.practice.jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Optional;
import java.util.Properties;

/**
 * JDBC工具类
 */
public class JdbcUtils {
	private static String driver;
	private static String url;
	private static String username;
	private static String password;
	private static Properties properties = new Properties();


	static {
		try {
			//如果使用getResourceAsStream，里面的路径需要满足：pom文件中指定资源文件路径+本路径=从项目目录为根节点算起的相对路径
			//pom文件中配置<resource>
			//                <directory>src</directory>
			//那么这边的路径：main/java/wangdao/practice/jdbc/jdbc.properties
			//pom文件中配置<resource>
			//                <directory>src/main/java</directory>
			//那么这边的路径：
			InputStream resourceAsStream = JdbcUtils.class.getClassLoader().getResourceAsStream("wangdao/practice/jdbc/jdbc.properties");
			//如果使用IO包中的File、FileInputStream等，路径就是从项目根节点算起的路径
			//InputStream resourceAsStream = new FileInputStream("src/main/java/wangdao/practice/jdbc/jdbc.properties");
			properties.load(resourceAsStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		driver = properties.getProperty("driver");
		url = properties.getProperty("url");
		username = properties.getProperty("username");
		password = properties.getProperty("password");
	}

	public static Connection getConnection() {
		try {
			Class.forName(driver);
			return DriverManager.getConnection(url, username, password);
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void close(ResultSet resultSet, Statement statement, Connection connection) throws SQLException {
		Optional.of(resultSet).ifPresent(r -> {
			try {
				r.close();
			} catch (SQLException throwables) {
				throwables.printStackTrace();
			}
		});
		Optional.of(statement).ifPresent(s -> {
			try {
				s.close();
			} catch (SQLException throwables) {
				throwables.printStackTrace();
			}
		});
		Optional.of(connection).ifPresent(c -> {
			try {
				c.close();
			} catch (SQLException throwables) {
				throwables.printStackTrace();
			}
		});
	}
}
